const Exercise = require('../models/Exercise');
const mongoose = require('mongoose');

/**
 * 获取用户的运动记录列表
 * @route GET /api/exercises
 * @param {string} startDate - 开始日期(yyyy-MM-dd)，可选
 * @param {string} endDate - 结束日期(yyyy-MM-dd)，可选
 * @param {string} type - 运动类型，可选
 * @returns {Array} 运动记录列表
 */
exports.getExercises = async (req, res) => {
  try {
    const { startDate, endDate, type } = req.query;
    const userId = req.user._id;
    
    // 构建查询条件
    const query = { user: userId };
    
    // 添加日期范围筛选
    if (startDate || endDate) {
      query.date = {};
      if (startDate) {
        query.date.$gte = new Date(startDate);
      }
      if (endDate) {
        // 将endDate设置为当天的23:59:59，以包含整天
        const endDateTime = new Date(endDate);
        endDateTime.setHours(23, 59, 59, 999);
        query.date.$lte = endDateTime;
      }
    }
    
    // 添加运动类型筛选
    if (type) {
      query.type = type;
    }
    
    // 查询并按日期降序排序
    const exercises = await Exercise.find(query)
      .sort({ date: -1, startTime: -1 });
    
    // 计算总消耗卡路里
    const totalCalories = exercises.reduce((sum, exercise) => sum + exercise.caloriesBurned, 0);
    
    res.status(200).json({
      success: true,
      count: exercises.length,
      totalCalories,
      data: exercises
    });
  } catch (error) {
    console.error('获取运动记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取运动记录失败',
      error: error.message
    });
  }
};

/**
 * 获取单个运动记录详情
 * @route GET /api/exercises/:id
 * @param {string} id - 运动记录ID
 * @returns {Object} 运动记录详情
 */
exports.getExerciseById = async (req, res) => {
  try {
    const exercise = await Exercise.findById(req.params.id);
    
    if (!exercise) {
      return res.status(404).json({
        success: false,
        message: '未找到运动记录'
      });
    }
    
    // 确保只能访问自己的运动记录
    if (exercise.user.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权访问此运动记录'
      });
    }
    
    res.status(200).json({
      success: true,
      data: exercise
    });
  } catch (error) {
    console.error('获取运动记录详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取运动记录详情失败',
      error: error.message
    });
  }
};

/**
 * 推断运动类别
 * @param {string} type 运动类型
 * @returns {string} 运动类别
 */
function inferExerciseCategory(type) {
  // 有氧运动类型
  const aerobicTypes = [
    '快走', '慢跑', '骑自行车', '游泳', '跳舞', '广场舞', 
    '太极拳', '椭圆机', '爬楼梯', '跳绳', '球类运动', '划船机'
  ];
  
  // 抗阻训练类型
  const resistanceTypes = [
    '健身', '哑铃训练', '杠铃训练', '器械训练', '弹力带', 
    '俯卧撑', '深蹲', '仰卧起坐', '引体向上', '卧推', 
    '壶铃', '爆发力训练'
  ];
  
  // 柔韧与平衡类型
  const flexibilityTypes = [
    '瑜伽', '八段锦', '拉伸', '静态伸展', '动态伸展', 
    '平衡训练', '关节活动度训练', '舒展运动'
  ];
  
  if (aerobicTypes.includes(type)) return '有氧运动';
  if (resistanceTypes.includes(type)) return '抗阻训练';
  if (flexibilityTypes.includes(type)) return '柔韧与平衡';
  return '有氧运动'; // 默认归类为有氧运动
}

/**
 * 创建新的运动记录
 * @route POST /api/exercises
 * @param {Object} body - 运动记录数据
 * @returns {Object} 创建的运动记录
 */
exports.createExercise = async (req, res) => {
  try {
    const {
      type,
      category,
      date,
      startTime,
      duration,
      intensity,
      caloriesBurned,
      glucoseBefore,
      glucoseAfter,
      notes
    } = req.body;
    
    // 验证必要字段
    if (!type || !date || !startTime || !duration || !intensity || !caloriesBurned) {
      return res.status(400).json({
        success: false,
        message: '请提供所有必要的运动信息'
      });
    }
    
    // 推断运动类别（如果未提供）
    const exerciseCategory = category || inferExerciseCategory(type);
    
    // 创建新的运动记录
    const exercise = new Exercise({
      user: req.user._id,
      type,
      category: exerciseCategory,
      date: new Date(date),
      startTime,
      duration,
      intensity,
      caloriesBurned,
      glucoseBefore,
      glucoseAfter,
      notes
    });
    
    await exercise.save();
    
    res.status(201).json({
      success: true,
      message: '成功创建运动记录',
      data: exercise
    });
  } catch (error) {
    console.error('创建运动记录失败:', error);
    res.status(500).json({
      success: false,
      message: '创建运动记录失败',
      error: error.message
    });
  }
};

/**
 * 更新运动记录
 * @route PUT /api/exercises/:id
 * @param {string} id - 运动记录ID
 * @param {Object} body - 更新的运动记录数据
 * @returns {Object} 更新后的运动记录
 */
exports.updateExercise = async (req, res) => {
  try {
    const {
      type,
      category,
      date,
      startTime,
      duration,
      intensity,
      caloriesBurned,
      glucoseBefore,
      glucoseAfter,
      notes
    } = req.body;
    
    // 查找现有运动记录
    let exercise = await Exercise.findById(req.params.id);
    
    if (!exercise) {
      return res.status(404).json({
        success: false,
        message: '未找到运动记录'
      });
    }
    
    // 确保只能更新自己的运动记录
    if (exercise.user.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权更新此运动记录'
      });
    }

    // 处理类型变更和类别推断
    const newType = type || exercise.type;
    const newCategory = category || (type ? inferExerciseCategory(newType) : exercise.category);
    
    // 更新运动记录字段
    exercise.type = newType;
    exercise.category = newCategory;
    exercise.date = date ? new Date(date) : exercise.date;
    exercise.startTime = startTime || exercise.startTime;
    exercise.duration = duration || exercise.duration;
    exercise.intensity = intensity || exercise.intensity;
    exercise.caloriesBurned = caloriesBurned || exercise.caloriesBurned;
    
    // 更新可选字段
    if (glucoseBefore !== undefined) exercise.glucoseBefore = glucoseBefore;
    if (glucoseAfter !== undefined) exercise.glucoseAfter = glucoseAfter;
    if (notes !== undefined) exercise.notes = notes;
    
    // 保存更新后的运动记录
    await exercise.save();
    
    res.status(200).json({
      success: true,
      message: '成功更新运动记录',
      data: exercise
    });
  } catch (error) {
    console.error('更新运动记录失败:', error);
    res.status(500).json({
      success: false,
      message: '更新运动记录失败',
      error: error.message
    });
  }
};

/**
 * 删除运动记录
 * @route DELETE /api/exercises/:id
 * @param {string} id - 运动记录ID
 * @returns {Object} 删除确认
 */
exports.deleteExercise = async (req, res) => {
  try {
    const exercise = await Exercise.findById(req.params.id);
    
    if (!exercise) {
      return res.status(404).json({
        success: false,
        message: '未找到运动记录'
      });
    }
    
    // 确保只能删除自己的运动记录
    if (exercise.user.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权删除此运动记录'
      });
    }
    
    // 删除运动记录
    await exercise.remove();
    
    res.status(200).json({
      success: true,
      message: '成功删除运动记录',
      data: {}
    });
  } catch (error) {
    console.error('删除运动记录失败:', error);
    res.status(500).json({
      success: false,
      message: '删除运动记录失败',
      error: error.message
    });
  }
};

/**
 * 获取用户每周运动统计
 * @route GET /api/exercises/stats/weekly
 * @returns {Object} 每周运动统计
 */
exports.getWeeklyStats = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 计算当前周的开始和结束日期
    const now = new Date();
    const dayOfWeek = now.getDay(); // 0是周日，1是周一，依此类推
    const startOfWeek = new Date(now);
    startOfWeek.setDate(now.getDate() - dayOfWeek);
    startOfWeek.setHours(0, 0, 0, 0);
    
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    endOfWeek.setHours(23, 59, 59, 999);
    
    // 查询本周的所有运动记录
    const weeklyExercises = await Exercise.find({
      user: userId,
      date: { $gte: startOfWeek, $lte: endOfWeek }
    });
    
    // 计算有氧运动分钟数
    const aerobicExercises = weeklyExercises.filter(exercise => 
      exercise.category === '有氧运动' || inferExerciseCategory(exercise.type) === '有氧运动'
    );
    
    const aerobicMinutes = aerobicExercises.reduce((total, exercise) => {
      return total + exercise.duration;
    }, 0);
    
    // 获取每周目标
    const weeklyGoals = {
      aerobicMinutes: 150, // 每周建议150分钟中等强度有氧运动
      resistanceCount: 2, // 每周建议2次力量训练
      flexibilityCount: 2 // 每周建议2次柔韧与平衡训练
    };
    
    // 计算力量训练次数
    const resistanceCount = weeklyExercises.filter(
      exercise => {
        // 抗阻训练类型
        const resistanceTypes = [
          '健身', '哑铃训练', '杠铃训练', '器械训练', '弹力带', 
          '俯卧撑', '深蹲', '仰卧起坐', '引体向上', '卧推', 
          '壶铃', '爆发力训练'
        ];
        
        return resistanceTypes.includes(exercise.type) || 
              (exercise.category === '抗阻训练');
      }
    ).length;
    
    // 计算柔韧与平衡训练次数
    const flexibilityCount = weeklyExercises.filter(
      exercise => {
        // 柔韧与平衡类型
        const flexibilityTypes = [
          '瑜伽', '八段锦', '拉伸', '静态伸展', '动态伸展', 
          '平衡训练', '关节活动度训练', '舒展运动'
        ];
        
        return flexibilityTypes.includes(exercise.type) || 
              (exercise.category === '柔韧与平衡');
      }
    ).length;
    
    // 计算目标完成百分比
    const aerobicProgress = Math.min(100, Math.round((aerobicMinutes / weeklyGoals.aerobicMinutes) * 100));
    const resistanceProgress = Math.min(100, Math.round((resistanceCount / weeklyGoals.resistanceCount) * 100));
    const flexibilityProgress = Math.min(100, Math.round((flexibilityCount / weeklyGoals.flexibilityCount) * 100));
    
    // 获取每日运动数据
    const dailyStats = [];
    for (let i = 0; i < 7; i++) {
      const day = new Date(startOfWeek);
      day.setDate(startOfWeek.getDate() + i);
      
      const nextDay = new Date(day);
      nextDay.setDate(day.getDate() + 1);
      
      // 查找当天的运动记录
      const dailyExercises = weeklyExercises.filter(exercise => {
        const exerciseDate = new Date(exercise.date);
        return exerciseDate >= day && exerciseDate < nextDay;
      });
      
      // 计算当天数据
      const dayCalories = dailyExercises.reduce((sum, ex) => sum + ex.caloriesBurned, 0);
      const dayMinutes = dailyExercises.reduce((sum, ex) => sum + ex.duration, 0);
      
      dailyStats.push({
        day: day.toISOString().split('T')[0],
        dayName: ['日', '一', '二', '三', '四', '五', '六'][day.getDay()],
        exercises: dailyExercises,
        count: dailyExercises.length,
        minutes: dayMinutes,
        calories: dayCalories
      });
    }
    
    res.status(200).json({
      success: true,
      data: {
        weekRange: `${startOfWeek.toISOString().split('T')[0]} to ${endOfWeek.toISOString().split('T')[0]}`,
        aerobicMinutes,
        aerobicGoal: weeklyGoals.aerobicMinutes,
        aerobicProgress,
        resistanceCount,
        resistanceGoal: weeklyGoals.resistanceCount,
        resistanceProgress,
        flexibilityCount,
        flexibilityGoal: weeklyGoals.flexibilityCount,
        flexibilityProgress,
        totalExercises: weeklyExercises.length,
        totalCaloriesBurned: weeklyExercises.reduce((sum, ex) => sum + ex.caloriesBurned, 0),
        dailyStats
      }
    });
  } catch (error) {
    console.error('获取每周运动统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取每周运动统计失败',
      error: error.message
    });
  }
};

/**
 * 获取支持的运动类型
 * @route GET /api/exercises/types
 * @returns {Array} 支持的运动类型列表
 */
exports.getExerciseTypes = (req, res) => {
  const exerciseTypes = [
    // 有氧运动
    { id: '快走', name: '快走', icon: '🚶', caloriesPerMinute: 4 },
    { id: '慢跑', name: '慢跑', icon: '🏃', caloriesPerMinute: 7 },
    { id: '骑自行车', name: '骑自行车', icon: '🚴', caloriesPerMinute: 6 },
    { id: '游泳', name: '游泳', icon: '🏊', caloriesPerMinute: 6 },
    { id: '跳舞', name: '跳舞', icon: '💃', caloriesPerMinute: 5 },
    { id: '广场舞', name: '广场舞', icon: '💃', caloriesPerMinute: 5 },
    { id: '太极拳', name: '太极拳', icon: '🧘', caloriesPerMinute: 3 },
    { id: '椭圆机', name: '椭圆机', icon: '🏋️', caloriesPerMinute: 5 },
    { id: '爬楼梯', name: '爬楼梯', icon: '🏢', caloriesPerMinute: 6 },
    { id: '跳绳', name: '跳绳', icon: '⏱️', caloriesPerMinute: 10 },
    { id: '球类运动', name: '球类运动', icon: '⚽', caloriesPerMinute: 6 },
    { id: '划船机', name: '划船机', icon: '🚣', caloriesPerMinute: 7 },
    
    // 抗阻训练
    { id: '健身', name: '健身', icon: '💪', caloriesPerMinute: 4 },
    { id: '哑铃训练', name: '哑铃训练', icon: '💪', caloriesPerMinute: 4 },
    { id: '杠铃训练', name: '杠铃训练', icon: '🏋️', caloriesPerMinute: 4 },
    { id: '器械训练', name: '器械训练', icon: '🔧', caloriesPerMinute: 4 },
    { id: '弹力带', name: '弹力带', icon: '🧵', caloriesPerMinute: 3 },
    { id: '俯卧撑', name: '俯卧撑', icon: '🙇', caloriesPerMinute: 4 },
    { id: '深蹲', name: '深蹲', icon: '🧎', caloriesPerMinute: 4 },
    { id: '仰卧起坐', name: '仰卧起坐', icon: '🧍', caloriesPerMinute: 3 },
    { id: '引体向上', name: '引体向上', icon: '🧗', caloriesPerMinute: 4 },
    { id: '卧推', name: '卧推', icon: '🏋️', caloriesPerMinute: 4 },
    { id: '壶铃', name: '壶铃', icon: '🔔', caloriesPerMinute: 4 },
    { id: '爆发力训练', name: '爆发力训练', icon: '⚡', caloriesPerMinute: 6 },
    
    // 柔韧与平衡
    { id: '瑜伽', name: '瑜伽', icon: '🧘‍♀️', caloriesPerMinute: 3 },
    { id: '八段锦', name: '八段锦', icon: '🧍‍♂️', caloriesPerMinute: 3 },
    { id: '拉伸', name: '拉伸', icon: '🤸', caloriesPerMinute: 2 },
    { id: '静态伸展', name: '静态伸展', icon: '🧠', caloriesPerMinute: 2 },
    { id: '动态伸展', name: '动态伸展', icon: '🤸‍♂️', caloriesPerMinute: 3 },
    { id: '平衡训练', name: '平衡训练', icon: '🧍‍♀️', caloriesPerMinute: 3 },
    { id: '关节活动度训练', name: '关节活动度训练', icon: '🔄', caloriesPerMinute: 2 },
    { id: '舒展运动', name: '舒展运动', icon: '🌈', caloriesPerMinute: 2 }
  ];
  
  res.status(200).json({
    success: true,
    data: exerciseTypes
  });
}; 